//
//  AppDelegate_JPush.m
//  Hipay_uuTianfu
//
//  Created by Mac on 16/5/5.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "AppDelegate_JPush.h"
#import "JPUSHService.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AdSupport/AdSupport.h>
#import "SystemMessageViewController.h"
#import "StateChangeViewController.h"
#import "ContenxtMessageViewController.h"
#import "DicuessMessageViewController.h"
#import "HomeViewController.h"
#import "PersonCenterViewController.h"
#import "DiscussViewController.h"
#import "EmergencySignViewController.h"
// iOS10注册APNs所需头文件
#pragma mark*******配置 ios 10
#import <UserNotifications/UserNotifications.h>
static NSString *appKey = @"61e47e19e573dc7f2179ade7";//个人证书key

static NSString *channel = @"Apple Store";
#ifdef C_DEBUG
static BOOL isProduction = FALSE;
#else
static BOOL isProduction = TRUE;
#endif
@interface AppDelegate(JPush)<JPUSHRegisterDelegate>
@end
@implementation AppDelegate(JPush)
- (void) initJPushApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
#pragma mark*******配置 ios 10
    /// ios 10
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    //Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    }
    else
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
            //可以添加自定义categories
            [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                              UIUserNotificationTypeSound |
                                                              UIUserNotificationTypeAlert)
                                                  categories:nil];
        }
        else {
            //categories 必须为nil
            [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                              UIRemoteNotificationTypeSound |
                                                              UIRemoteNotificationTypeAlert)
                                                  categories:nil];
        }
    
#pragma mark*******配置 ios 10
    
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:advertisingId];
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0)
        {
            // iOS10获取registrationID放到这里了, 可以存到缓存里, 用来标识用户单独发送推送
            echo(([NSString stringWithFormat:@"registrationID获取成功：%@", registrationID]));
            [[NSUserDefaults standardUserDefaults] setObject:registrationID forKey:@"registrationID"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        else
        {
            echo(([NSString stringWithFormat:@"registrationID获取失败，code：%d",resCode]));

        }
    }];
    
    
}

- (void)JPushApplicationDidEnterBackground:(UIApplication *)application {
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
    [JPUSHService setBadge:0];
    [JPUSHService clearAllLocalNotifications];
}

- (void)JPushApplicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
    [JPUSHService setBadge:0];
    [JPUSHService clearAllLocalNotifications];
}
//注册APNs成功并上报DeviceToken
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [JPUSHService registerDeviceToken:deviceToken];
    if (![CClass hasCacheData:@"NoPush"]) {
        [self registerJPush];
    }
    
}
//实现注册APNs失败接口（可选） 注册失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
        echo(([NSString stringWithFormat:@"did Fail To Register For Remote Notifications With Error: %@", error]));

}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void (^)())completionHandler {
}



- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler {
}
#endif
//  // 只有ios7
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
 
    [JPUSHService handleRemoteNotification:userInfo];
    PostNotification(NSN_NewPushMessage);

    //在前台
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {

    }else
    {//在后台
        NSString* type=[userInfo objectForKey:@"type"];
        [self goToMessageViewWith:type];
    }

    //    [application setApplicationIconBadgeNumber:application.applicationIconBadgeNumber];
    [application setApplicationIconBadgeNumber:0];
}
//iOS 7 Remote Notification
//接收 iOS10以下版本时 支持的 8 9
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    //iOS7及以上系统，收到通知
    // apn 内容获取：
    [JPUSHService handleRemoteNotification:userInfo];
    //在前台
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        
    }else
    {//在后台
        NSString* type=[userInfo objectForKey:@"type"];
        [self goToMessageViewWith:type];
    }

    completionHandler(UIBackgroundFetchResultNewData);
    PostNotification(NSN_NewPushMessage);
    [self alertShow];
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}

- (void) registerJPush{
    [JPUSHService setAlias:[CClass getUUID] callbackSelector:nil object:nil];
    [CClass saveCacheData:nil key:@"NoPush"];
}

- (void) unRegisterJPush{
    [JPUSHService setAlias:@"" callbackSelector:nil object:nil];
    [CClass saveCacheData:@"noPush" key:@"NoPush"];
}

- (void) alertShow{
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    AudioServicesPlaySystemSound(1007);
}
#pragma mark - iOS10: 收到推送消息调用(iOS10是通过Delegate实现的回调)
#pragma mark- JPUSHRegisterDelegate
#pragma mark*******配置 ios 10

// iOS 10 Support iOS10及以上版本时
//// 当程序在前台时, 收到推送弹出的通知

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
//        NSString* type=[userInfo objectForKey:@"type"];
//        [self goToMessageViewWith:type];
        PostNotification(NSN_NewPushMessage);

        
    }else
    {
        // 本地通知
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
// 程序关闭后, 通过点击推送弹出的通知

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        PostNotification(NSN_NewPushMessage);

        NSString* type=[userInfo objectForKey:@"type"];
        [self goToMessageViewWith:type];
    }else
    {
        // 本地通知
    }
    completionHandler();  // 系统要求执行这个方法
}
- (void)goToMessageViewWith:(NSString *)type
{
    MainNavBarViewController * nav = (MainNavBarViewController *)self.window.rootViewController;
    CBaseController *c = nav.viewControllers.firstObject;
    if (c.mainTabBar.selectIndex == 0) {
        
    }else{
        [c pushController:nil Lever:99 Animated:NO];
        c.mainTabBar.showIndex = 0;

    }
    MainNavBarViewController *childnav = [c.mainTabBar tabBarItem:0].controller;
    
    if ([type isEqualToString:@"1"]) {
        //系统
        
        SystemMessageViewController * VC = [[SystemMessageViewController alloc]init];
        VC.type=@"推送";
        [childnav pushViewController:VC animated:YES];

//        MainNavBarViewController *navigationController = (MainNavBarViewController *)self.window.rootViewController;
//        [navigationController pushViewController:VC animated:YES];
        
    }else if ([type isEqualToString:@"2"]){
        //任务变更
        StateChangeViewController * VC = [[StateChangeViewController alloc]init];
        VC.type=@"推送";
        [childnav pushViewController:VC animated:YES];

    }else if ([type isEqualToString:@"3"])
    {
        //留言
        
        ContenxtMessageViewController * VC = [[ContenxtMessageViewController alloc]init];
        VC.type=@"推送";
        [childnav pushViewController:VC animated:YES];

    }else if ([type isEqualToString:@"4"])
    {
        //讨论
        DicuessMessageViewController * VC = [[DicuessMessageViewController alloc]init];
        VC.type=@"推送";
        [childnav pushViewController:VC animated:YES];

    }else if ([type isEqualToString:@"5"])
    {
        EmergencySignViewController *emergencyVC=[[EmergencySignViewController alloc]init];
        emergencyVC.type=@"推送";
        [childnav pushViewController:emergencyVC animated:YES];
    }
    

}

@end
